<template>
  <div class="poscontent">
    <div class="flex flexrowbetween bg_fff flexwrapper headerbox mb_14">
      <el-form :inline="true" :model="params" class="forminline mb_10">
        <el-form-item label="广告类型" class="mb_0">
          <el-select
            v-model="params.position_id"
            size="small"
            placeholder="请选择广告类型"
            @change="handleQuery"
          >
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="(item, index) in positionlist"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="平台" class="mb_0">
          <el-select
            v-model="params.plate_id"
            size="small"
            placeholder="请选择平台"
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="(item, index) in platelist"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="mb_0">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="handleQuery"
          >搜索
          </el-button>
        </el-form-item>
      </el-form>
      <div class="flex aligncenter mb_10">
        <div
          v-for="(item, index) in days"
          :key="index"
          class="dataname f-14 commhover"
          :class="{ active: daynum == item.value }"
          @click="handleClick(item)"
        >
          {{ item.name }}
        </div>
        <el-date-picker
          class="mr_20"
          v-model="time"
          size="small"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="changeTime"
        >
        </el-date-picker>
        <!--         <el-button-->
        <!--          plain-->
        <!--          type="primary"-->
        <!--          class="exportbtn"-->
        <!--          size="small"-->
        <!--          @click="handleExport"-->
        <!--          >导出</el-button-->
        <!--        >-->
      </div>
    </div>
    <div class="bg_fff boxflex mb_20">
      <div class="flex f-16 c_000 aligncenter mb_20">
        <div class="line mr_10"></div>
        关键数据
      </div>
      <el-row :gutter="20">
        <el-col :span="27">
          <div class="coinitem c_000 flexrowbetween">
            <div class="flexcolumn l_text">
              <div class="mb_15 f-14">拉取量</div>
              <div class="f-20 f_w5">{{ datainfo.get }}</div>
            </div>
            <img src="@/assets/images/bianji.png" alt="" class="r_img"/>
          </div>
        </el-col>
        <el-col :span="27">
          <div class="coinitem c_000 flexrowbetween">
            <div class="flexcolumn l_text">
              <div class="mb_15 f-14">曝光量</div>
              <div class="f-20 f_w5">{{ datainfo.broke }}</div>
            </div>
            <img src="@/assets/images/jiaosecaidan.png" alt="" class="r_img"/>
          </div>
        </el-col>
        <el-col :span="27">
          <div class="coinitem c_000 flexrowbetween">
            <div class="flexcolumn l_text">
              <div class="mb_15 f-14">曝光率</div>
              <div class="f-20 f_w5">{{ datainfo.transform_ratio }} %</div>
            </div>
            <img src="@/assets/images/jiaosecaidan.png" alt="" class="r_img"/>
          </div>
        </el-col>
        <el-col :span="27">
          <div class="coinitem c_000 flexrowbetween">
            <div class="flexcolumn l_text">
              <div class="mb_15 f-14">点击量</div>
              <div class="f-20 f_w5">{{ datainfo.click }}</div>
            </div>
            <img src="@/assets/images/click.png" alt="" class="r_img"/>
          </div>
        </el-col>
        <el-col :span="27">
          <div class="coinitem c_000 flexrowbetween">
            <div class="flexcolumn l_text">
              <div class="mb_15 f-14">点击率</div>
              <div class="f-20 f_w5">{{ datainfo.click_ratio }} %</div>
            </div>
            <img src="@/assets/images/click.png" alt="" class="r_img"/>
          </div>
        </el-col>
        <el-col :span="27">
          <div class="coinitem c_000 flexrowbetween">
            <div class="flexcolumn l_text">
              <div class="mb_15 f-14">ecpm</div>
              <div class="f-20 f_w5">{{ datainfo.ecpm }}</div>
            </div>
            <img src="@/assets/images/ecpm.png" alt="" class="r_img"/>
          </div>
        </el-col>
        <el-col :span="27">
          <div class="coinitem c_000 flexrowbetween">
            <div class="flexcolumn l_text">
              <div class="mb_15 f-14">收入</div>
              <div class="f-20 f_w5">{{ datainfo.score }}</div>
            </div>
            <img src="@/assets/images/income.png" alt="" class="r_img"/>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="bg_fff boxflex mb_20">
      <div class="flex f-16 c_000 aligncenter mb_20">
        <div class="line mr_10"></div>
        关键指标趋势图
      </div>
      <div class="flex aligncenter mb_30">
        <div class="f-14 c_000 mr_30">数据指标</div>
        <el-checkbox-group v-model="resource">
          <!-- <el-radio label="" class="mr_30">全部</el-radio> -->
          <el-checkbox
            v-for="(item, index) in typeList"
            :key="index"
            :label="item.id"
            class="mr_30"
            @change="changeType"
          >
            <span class="colorbox" :style="{ background: item.color }"></span>
            <template v-if="item.tip">
              <el-tooltip class="item" effect="light" :content="item.tip" placement="top-start">
                <span>{{ item.name }}</span>
              </el-tooltip>
            </template>
            <template v-else>
              <span>{{ item.name }}</span>
            </template>
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <div>
        <line-chart
          :key="keys"
          :legendname="checkTypelist"
          :xAxis="xAxis"
          :chartData="lineChartData"
          height="360px"
        />
      </div>
    </div>

    <div class="bg_fff boxflex">
      <div class="flexrowbetween">
        <div class="flex f-16 c_000 aligncenter mb_20">
          <div class="line mr_10"></div>
          {{ dayname }}数据明细
        </div>
        <div class="mt_3">
          <el-button
            plain
            size="small"
            type="primary"
            class="exportbtn mb_10"
            @click="handleExport"
            v-hasPermi="['incomedetail:export']"
          >
            导出
          </el-button>
        </div>
      </div>
      <div class="">
        <el-table
          v-loading="loading"
          :data="tableData"
          ref="tablelayout"
          class="commtable"
        >
          <el-table-column
            align="center"
            label="时间"
            prop="time"
            min-width="120"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            align="center"
            label="拉取量"
            min-width="100"
            prop="user_login"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.data.get }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="曝光量"
            prop="mobile"
            min-width="100"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.data.broke }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="曝光率%"
            prop="mobile"
            min-width="120"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.data.transform_ratio }} %</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="点击量"
            prop="email"
            min-width="100"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.data.click }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="点击率（%）"
            prop="last_login_time"
            min-width="120"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{ scope.row.data.click_ratio }} %
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="ecpm"
            min-width="200"
            prop="create_time"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{ scope.row.data.ecpm }}
            </template>
          </el-table-column>
          <el-table-column
            label="收入"
            align="center"
            min-width="100"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.data.score }}</span>
            </template>
          </el-table-column>
        </el-table>
        <!-- <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.page"
          :limit.sync="queryParams.num"
          @pagination="getList"
        /> -->
      </div>
    </div>
  </div>
</template>

<script>
import {
  allData,
  trendHourChart,
  trendDayChart,
  trendMonthChart, reqTrendHourChartExport, reqTrendDayChartExport, reqTrendMonthChartExport
} from '@/api/income'
import { time_date } from '@/utils/validate'
import LineChart from '@/components/Echart/LineChart'
import { reqPlanWorkIndexExport } from '@/api/advergroupPlanMgt'

export default {
  data() {
    return {
      queryParams: {
        page: 1,
        num: 10
      },
      params: {
        position_id: '',
        plate_id: ''
      },
      positionlist: [],
      platelist: [],
      time: '',
      loading: false,
      dayname: '昨日',
      days: [
        { name: '昨日', value: 1 },
        { name: '今日', value: 2 },
        { name: '本月', value: 3 },
        { name: '全年', value: 4 }
      ],
      tableColumns: [
        { key: 'time', label: `时间`, visible: true },
        { key: 'get', label: `拉取量`, visible: true },
        { key: 'broke', label: `曝光量`, visible: true },
        { key: 'transform_ratio', label: `曝光率（%）`, visible: true },
        { key: 'click', label: `点击量`, visible: true },
        { key: 'click_ratio', label: `点击率（%）`, visible: true },
        { key: 'ecpm', label: `ecpm` },
        { key: 'score', label: `收入`, visible: true }
      ],
      paramsForm: [],
      exportColumns: [
        { key: 'time', label: `时间` },
        { key: 'data.get', label: `拉取量` },
        { key: 'data.broke', label: `曝光量` },
        { key: 'data.transform_ratio', label: `曝光率（%）` },
        { key: 'data.click', label: `点击量` },
        { key: 'data.click_ratio', label: `点击率（%）` },
        { key: 'data.ecpm', label: `ecpm` },
        { key: 'data.score', label: `收入` }
      ],
      daynum: 1,
      datainfo: {
        broke: 0,
        click: 0,
        click_ratio: 0,
        get: 0,
        score: 0,
        transform_ratio: 0,
        ecpm: 0
      },
      tableData: [],
      total: 0,
      typeList: [
        { id: 'get', name: '拉取量', value: 1, color: '#1670F1', tip: '当用户打开H5时，平台拉取广告于广告位，页面加载完成，说明当前用户广告拉取量为1.' },
        { id: 'broke', name: '曝光量', value: 2, color: '#62B088', tip: '广告展示给用户的次数。计算方式: 经平台判定有效且被计费的展示次数' },
        {
          id: 'transform_ratio',
          name: '曝光率（%）',
          value: 3,
          color: '#E50000',
          tip: '广告时间范围内广告实际到达的人数/可以覆盖人群总数=曝光率(曝光量/拉取量)'
        },
        { id: 'click', name: '点击量', value: 4, color: '#F8C96B', tip: '当用户点击广告素材时，触发点击事件，该事件被认为是一次有效的广告点击' },
        { id: 'click_ratio', name: '点击率（%）', value: 5, color: '#6D48E4', tip: '广告被点击的次数占展示次数的百分比。计算方法:点击数/展示数100%' },
        { id: 'ecpm', name: 'ecpm', value: 6, color: '#2D5D81', tip: '广告平均每一千次展现所付出的广告币，计算公式是: 总消耗/展示数*1000' },
        { id: 'score', name: '收入', value: 7, color: '#1E2F4D' }
      ],
      resource: [],
      lineChartData: {
        // get: [],
        // broke: [],
        // transform_ratio: [],
        // click: [],
        // click_ratio: [],
        // ecpm: [],
        // score: [],
      },
      xAxis: [],
      keys: ''
    }
  },
  components: {
    LineChart
  },
  created() {
    this.getDicts('/manager/api/planPositionList').then((res) => {
      this.positionlist = res.data
    })
    this.getDicts('/manager/api/getPlateList').then((res) => {
      this.platelist = res.data
    })
    this.typeList.forEach((item) => {
      this.resource.push(item.id)
    })
    this.getData()
    this.getList()
  },
  computed: {
    checkTypelist() {
      let arr = []
      this.typeList.forEach((item) => {
        if (this.resource.includes(item.id)) {
          arr.push(item)
        }
      })
      // console.log('arr:', arr)
      return arr
      // this.resource.map
    }
  },
  methods: {
    getData() {
      let params = { ...this.queryParams }
      if (this.params.position_id) {
        params.position_id = this.params.position_id
      }
      if (this.params.plate_id) {
        params.plate_id = this.params.plate_id
      }
      if (this.time) {
        params.start = this.time[0]
        params.end = this.time[1]
      }
      if (this.daynum == 1) {
        params.start = this.parseTime(time_date(-1).start, '{y}-{m}-{d}')
        params.end = this.parseTime(time_date(-1).start, '{y}-{m}-{d}')
      }
      if (this.daynum == 2) {
        params.start = this.parseTime(time_date(1).start, '{y}-{m}-{d}')
        params.end = this.parseTime(time_date(1).end, '{y}-{m}-{d}')
      }
      if (this.daynum == 3) {
        params.start = this.parseTime(time_date(30).start, '{y}-{m}-{d}')
        params.end = this.parseTime(time_date(30).end, '{y}-{m}-{d}')
      }
      if (this.daynum == 4) {
        params.start = this.parseTime(time_date(365).start, '{y}-{m}-{d}')
        params.end = this.parseTime(time_date(365).end, '{y}-{m}-{d}')
      }
      this.loading = true
      allData(params)
        .then((res) => {
          this.loading = false
          this.datainfo = res.data
        })
        .catch(() => {
          this.loading = false
        })
    },

    handleClick(num) {
      this.daynum = num.value
      this.dayname = num.name
      this.time = ''
      this.handleQuery()
    },

    handleQuery() {
      this.queryParams.page = 1
      this.getData()
      this.getList()
    },

    changeTime(val) {
      if (val) {
        this.daynum = ''
      } else {
        this.daynum = 1
      }
      this.handleQuery()
    },

    getList() {
      if (this.daynum == 1 || this.daynum == 2) {
        this.trendHourChart()
      }
      if (this.daynum == 3) {
        this.trendDayChart()
      }
      if (this.daynum == 4) {
        this.trendMonthChart()
      }
      if (this.time) {
        this.trendDayChart()
      }
    },

    trendHourChart() {
      let params = { ...this.queryParams }
      if (this.params.position_id) {
        params.position_id = this.params.position_id
      }
      if (this.params.plate_id) {
        params.plate_id = this.params.plate_id
      }
      if (this.daynum == 1) {
        params.time = this.parseTime(time_date(-1).start, '{y}-{m}-{d}')
      }
      if (this.daynum == 2) {
        params.time = this.parseTime(time_date(1).start, '{y}-{m}-{d}')
      }
      this.loading = true
      this.paramsForm = params
      trendHourChart(params)
        .then((res) => {
          this.loading = false
          this.tableData = res.data
          this.changeLineData(res.data)
        })
        .catch(() => {
          this.loading = false
        })
    },

    trendDayChart() {
      let params = { ...this.queryParams }
      if (this.params.position_id) {
        params.position_id = this.params.position_id
      }
      if (this.params.plate_id) {
        params.plate_id = this.params.plate_id
      }
      if (this.daynum == 3) {
        params.start = this.parseTime(time_date(30).start, '{y}-{m}-{d}')
        params.end = this.parseTime(time_date(30).end, '{y}-{m}-{d}')
      }
      if (this.time) {
        params.start = this.time[0]
        params.end = this.time[1]
      }
      this.loading = true
      this.paramsForm = params;
      trendDayChart(params)
        .then((res) => {
          this.loading = false
          this.tableData = res.data
          this.changeLineData(res.data)
        })
        .catch(() => {
          this.loading = false
        })
    },

    trendMonthChart() {
      let params = { ...this.queryParams }
      if (this.params.position_id) {
        params.position_id = this.params.position_id
      }
      if (this.params.plate_id) {
        params.plate_id = this.params.plate_id
      }
      if (this.daynum == 4) {
        params.start = this.parseTime(time_date(365).start, '{y}-{m}-{d}')
        params.end = this.parseTime(time_date(365).end, '{y}-{m}-{d}')
      }
      if (this.time) {
        params.start = this.time[0]
        params.end = this.time[1]
      }
      this.loading = true;
      this.paramsForm = params;
      trendMonthChart(params)
        .then((res) => {
          this.loading = false
          this.tableData = res.data
          this.changeLineData(res.data)
        })
        .catch(() => {
          this.loading = false
        })
    },

    changeLineData(data) {
      // console.log(data);
      let params = {
        get: [],
        broke: [],
        transform_ratio: [],
        click: [],
        click_ratio: [],
        ecpm: [],
        score: []
      }
      data.forEach((item) => {
        params.get.push(item.data.get)
        params.broke.push(item.data.broke)
        params.transform_ratio.push(item.data.transform_ratio)
        params.click.push(item.data.click)
        params.click_ratio.push(item.data.click_ratio)
        params.ecpm.push(item.data.ecpm)
        params.score.push(item.data.score)
      })
      // console.log('this.resource:', this.resource)
      let p_params = {}
      this.resource.map((item) => {
        p_params[item] = params[item]
      })
      this.lineChartData = p_params
      this.xAxis = data.map((item) => item.time)
    },

    changeType() {
      console.log(this.resource)
      this.keys = Date.now()
      this.changeLineData(this.tableData)
    },

    handleExport() {
      let form = JSON.parse(JSON.stringify(this.paramsForm))
      let head = []
      let keys = []
      let list = []
      this.tableColumns.forEach(item => {
        list.push(item.label)
      })
      this.exportColumns.forEach(item => {
        if (list.indexOf(item.label) > -1) {
          if (head.indexOf(item.label) == -1) {
            head.push(item.label)
          }
          if (keys.indexOf(item.key) == -1) {
            keys.push(item.key)
          }
        }

      })
      form.head = head
      form.keys = keys

      delete form.page
      delete form.num
      let url = ''
      if (this.daynum == 1 || this.daynum == 2) {
        url = reqTrendHourChartExport
      }
      if (this.daynum == 3) {
        url = reqTrendDayChartExport
      }
      if (this.daynum == 4) {
        url = reqTrendMonthChartExport
      }
      if (this.time) {
        url = reqTrendDayChartExport
      }
      url(form).then((res) => {
        console.log('333', res)
        if (res.code == 1) {
          const a = document.createElement('a')
          document.body.appendChild(a)
          a.download = '广告主收益列表.xls'
          a.href = res.data
          a.click()
          document.body.removeChild(a)
        }

      })

    }
  }
}
</script>

<style lang="scss" scoped>
.poscontent {
  // 56 导航栏的高 46 tab的高度 35 padding的高度
  height: calc(100vh - 60px);
  padding: 16px 16px 0 6px;
  //   overflow-y: auto;
  overflow-x: hidden;
}

.headerbox {
  padding: 10px 15px 0;
}

.dataname {
  margin-right: 22px;
  color: #8e8e8e;
  position: relative;

  &.active {
    color: #000;
  }

  &.active::after {
    position: absolute;
    content: "";
    width: 28px;
    height: 2px;
    background-color: #1670f1;
    bottom: -6px;
    left: 0;
  }
}

.boxflex {
  padding: 16px 20px;

  .line {
    width: 2px;
    height: 18px;
    background-color: #1670f1;
  }
}

.coinitem {
  height: 110px;
  padding: 15px;
  border-radius: 6px;
  background-color: #f8f9fd;
}

.el-col-27 {
  width: 14.2%;
}

.r_img {
  width: 52px;
  height: 52px;
}

.l_text {
  padding-left: 5%;
}

.colorbox {
  display: inline-block;
  width: 20px;
  height: 10px;
  margin-right: 2px;
}

@media screen {
}
</style>
